package com.goodboys.controller;

import com.alibaba.fastjson.JSON;
import com.goodboys.base.controller.BaseController;
import com.goodboys.base.entity.BaseReqBean;
import com.goodboys.base.resp.Response;
import com.goodboys.base.webscoket.SocketSessionRegistry;
import com.goodboys.dao.InformationDao;
import com.goodboys.entity.*;
import com.goodboys.service.UserService;
import com.goodboys.utils.BaiduLocationUtils;
import com.goodboys.utils.GoldMantisUtil;
import com.goodboys.utils.PhoneFormatCheckUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by CJ on 2018-05-19.
 */
@RestController
@RequestMapping("/sys")
public class SysController extends BaseController{

    private final Logger logger = LoggerFactory.getLogger(SysController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private InformationDao informationDao;

    /**session操作类*/
    @Autowired
    SocketSessionRegistry webAgentSessionRegistry;
    /**消息发送工具*/
    @Autowired
    private SimpMessagingTemplate template;

    @PostMapping("/register")
    @ResponseBody
    public Response register(BaseReqBean baseReqBean){
        User user = new User();
        user.setPhone(baseReqBean.getPhone());
        user.setName(baseReqBean.getName());
        user.setType(baseReqBean.getType());
        user.setPwd(baseReqBean.getPwd());
        user.setTag(baseReqBean.getTag());

        Response response = new Response();
        try {
            Map map = userService.register(user);
            //发送至目标用户
            if((Integer)map.get("status")==1 && map.get("message") instanceof User) {
                webAgentSessionRegistry.getAllSessionIds().entrySet().stream()
                        .map(Map.Entry::getValue).flatMap(users -> users.stream().collect(Collectors.toList()).stream())
//                        .filter(user1 -> user1.getRange() <= BaiduLocationUtils.getDistance(new LngLat(user1.getLng(), user1.getLat()), new LngLat(baseReqBean.getLng(), baseReqBean.getLat())))
//                        .filter(user1 -> user1.getType() == baseReqBean.getType())
                        .forEach(user1 -> {
                                    template.convertAndSendToUser(user1.getSessionId(), "/topic/register", JSON.toJSONString(map), createHeaders(user1.getSessionId()));
                                  System.out.println(user1.getId());

                                }
                        );
            }
            return getRetunResult(map,response);
        } catch (Exception e) {
            logger.error("注册用户失败。。。");e.printStackTrace();
            return response.failure("用户注册失败。。。");
        }
    }

    //验证码登录方式
    @GetMapping("/dynamicLogin")
    @ResponseBody
    public Response dynamicLogin(@Param("code") String code){
        Response response = new Response();
        try {
//            Map result = userService.login(user);
//            return getRetunResult(result,response);
            return  null;
        } catch (Exception e) {
            logger.error("用户登录失败，请重试。。。");e.printStackTrace();
            return response.failure("用户登录失败，请重试。。。");
        }
    }


    @PostMapping("/login")
    @ResponseBody
    public Response login(User user){
        Response response = new Response();
        try {
            Map result = userService.login(user);
            return getRetunResult(result,response);
        } catch (Exception e) {
            logger.error("用户登录失败，请重试。。。");e.printStackTrace();
            return response.failure("用户登录失败，请重试。。。");
        }
    }

    //判断用户是够已经注册
    @GetMapping("/isRegister")
    @ResponseBody
    public Response isRegister(@Param("phone") String phone){
        Response response = new Response();
        try {
            Map result = userService.isExist(phone);
            return  getRetunResult(result,response);
        } catch (Exception e) {
            logger.error("查询附近用户失败，请重试。。。");e.printStackTrace();
            return response.failure("查询附近用户失败，请重试。。。");
        }
    }

    /**
     * 系统报错信息
     * @param message
     * @return
     */
    @GetMapping("/error")
    @ResponseBody
    public Response error(@Param("message") String message){
        Response response = new Response();
        return response.failure(message);
    }

    /**
     * 系统报错信息post
     * @param message
     * @return
     */
    @PostMapping("/postError")
    @ResponseBody
    public Response postError(@Param("message") String message){
        Response response = new Response();
        return response.failure(message);
    }

/*    @GetMapping("/ws")
    public ModelAndView ws(){
        return new ModelAndView("forward:/index.html");
    }*/


    @PostMapping("/addInfos")
    @ResponseBody
    public Map addInfos(InformationBean informationBean){
        Map map = new HashMap();
        if (StringUtils.isEmpty(informationBean.getUser_name()) || StringUtils.isEmpty(informationBean.getContent())) {
            map.put("message", "user_name或content为空，请重试。。。");
            map.put("status", -1);
            return  map;
        }else {
            map.put("status", 1);
            map.put("user_name", informationBean.getUser_name());
            informationBean.setUser_name(informationBean.getUser_name());
            //增加操作
                informationBean.setCreate_time(new Date());
            informationDao.addInfo(informationBean);
            map.put("content", informationBean.getContent());
            return map;
        }


    }

    @GetMapping("/getDetail")
    @ResponseBody
    public Map getDetail(@Param("user_name") String user_name){
        Map map = new HashMap();
        if (StringUtils.isEmpty(user_name)) {
            map.put("message", "user_name不能为空，请重试。。。");
            map.put("status", -1);
            return map;
        }else {
            map.put("status",1);
            map.put("user_name", user_name);
            List<String> infos = informationDao.getInfos(user_name);
            map.put("list", infos);
            return map;
        }

    }


    @GetMapping("/autoRead")
    @ResponseBody
    public Response autoRead(UserBean user){
        /*List<UserBean> list =  new ArrayList<>();
        //必须是用户工号
        list.add(new UserBean("N0047522", "chenjun18534@%"));*/
        if(user == null || StringUtils.isEmpty(user.getAccount()) || StringUtils.isEmpty(user.getPwd())) {
            return new Response().failure("参数不能为空。。。");
        }
        try {
                //阅读学习平台
                GoldMantisUtil.readArticle(user.getAccount());
                //阅读邮件
                GoldMantisUtil.readMail(user.getAccount(),user.getPwd());
                return new Response().success("订阅成功");
            } catch (IOException e) {
                e.printStackTrace();
                return new Response().failure("订阅失败");
            }
    }



}
